/**
 * TmHttpRunner.java<br>
 *
 * @author aaronwong.sd@foxmail.com
 * @version 下午10:20:45
 */
package com.iwechat.service.runner;

import java.util.concurrent.ConcurrentLinkedQueue;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iwechat.config.CommConst;
import com.iwechat.controller.TemplateMessageController;
import com.iwechat.httpclient.HttpClientUtil;
import com.iwechat.mybatis.generator.model.TemplateMessage;

/**
 * 模板消息http请求发送执行器
 *
 * @author aaronwong.sd@foxmail.com
 */
public class TmHttpRunner implements Runnable {
    private final ConcurrentLinkedQueue<TemplateMessage> passedMessagePool = MessageSender.passedMessagePool;
    private final HttpClientUtil                         httpUtil          = HttpClientUtil.getInstance();
    private String                                       url;
    private TemplateMessage                              message;

    public TmHttpRunner(String url, TemplateMessage message) {
        this.url = url;
        this.message = message;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Runnable#run()
     */
    @Override
    public void run() {
        JSONObject response = new JSONObject();
        response.put("errcode", TemplateMessageController.ERROR_SEND2WX_EMPTY_RESP);
        String respStr = null;
        try {
            respStr = send();
        } catch (Exception e1) {
        }

        if (respStr != null) {
            response = JSON.parseObject(respStr);
        }
        int code = 0;
        try {
            code = response.getIntValue("errcode");
        } catch (Exception e) {
            code = -1;
        }
        if (code == 0) {
            // 发送 成功
            message.setStatus(TemplateMessage.Status.STATUS_2_SUCCESS);
        } else {
            // 发送 失败
            message.setStatus(code);
        }
        passedMessagePool.offer(message);
    }

    private String send() throws Exception {
        String jsonContent = message.getJsoncontent();
        JSONObject sendJson = JSON.parseObject(jsonContent);
        sendJson.put(CommConst.SEQNB, message.getSeqnb());
        return httpUtil.sendPost(url, sendJson.toJSONString(), String.valueOf(message.getSeqnb())).getDataStr();
    }

}
